package com.hxgz.steel.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.hxgz.steel.common.ServerResponse;
import com.hxgz.steel.dao.*;
import com.hxgz.steel.domain.*;
import com.hxgz.steel.dto.*;
import com.hxgz.steel.service.ConsumerCenterService;
import com.hxgz.steel.service.NewOrderService;
import com.hxgz.steel.util.CommonUtils;

import java.math.BigInteger;
import java.util.*;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.NumberFormat;

@Service
@Transactional
public class ConsumerCenterServiceImp implements ConsumerCenterService {

    @Autowired
    private AskBuyMapper askBuyMapper;

    @Autowired
    private QuotationMapper quotationMapper;

    @Autowired
    private QuotationInfoMapper quotationInfoMapper;

    @Autowired
    private AskInfoMapper askInfoMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private NewOrderService newOrderService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SocerManagerMapper socerManagerMapper;

    @Override
    public ServerResponse check(User user, Page page, String startDate,
                                String endDate, Integer status) {
        HashMap<Object, Object> map = Maps.newHashMap();
        map.put("status", status);
        map.put("userId", user.getId());
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
        List<AskBuyDto> askBuyDtoList = askBuyMapper.getAskList(map);
        for (AskBuyDto askBuyDto : askBuyDtoList) {
            //统计平台求购匹配的商家总共有几家
            Integer count = quotationMapper.countNum(Integer.valueOf(askBuyDto.getAskBuyId()));
            //得到匹配商家里最新报价一家的的报价信息
            Quotation quotation = quotationMapper.getNewPrice(Integer.valueOf(askBuyDto.getAskBuyId()));
            //得到匹配商家里所有已经报价了的商家个数
            Integer countMerchant = quotationMapper.countNumByNull(Integer.valueOf(askBuyDto.getAskBuyId()));
            askBuyDto.setMatchMerchant(String.valueOf(count));
            askBuyDto.setOfferMerchant(String.valueOf(countMerchant));
            if (quotation != null) {
                askBuyDto.setNewPrice(String.valueOf(quotation.getPrice()));
            } else {
                askBuyDto.setNewPrice("0");
            }

        }
        PageInfo pageInfo = new PageInfo(askBuyDtoList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Override
    public ServerResponse checkOrder(Integer index, Integer status, Page page, String startDate,
                                     String endDate, User user) {
        HashMap<Object, Object> map = Maps.newHashMap();
        map.put("userId", user.getId());
        map.put("status", status);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        List<OrderDto> list1 = null;
//    PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
        if (1 != index) {
            //第三方订单
            PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
            list1 = orderMapper.getOrderListByZero(map);
            for (OrderDto orderDto : list1) {
                if (orderDto.getAnnualFee() == null) {
                    orderDto.setAnnualFeeStatus(0);
                } else {
                    orderDto.setAnnualFeeStatus(1);
                }
            }
        } else {
            //自营订单
            PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
            list1 = orderMapper.getOrderListByOne(map);
            for (OrderDto orderDto : list1) {
                List<OrderItem> orderItems = orderItemMapper.getOrderItem(orderDto.getId());
                orderDto.setList(orderItems);
                if (orderDto.getAnnualFee() == null) {
                    orderDto.setAnnualFeeStatus(0);
                } else {
                    orderDto.setAnnualFeeStatus(1);
                }
            }
        }
        PageInfo pageInfo = new PageInfo(list1);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse buyList(User user) {
        HashMap<Object, Object> map = Maps.newHashMap();
        /*今日求购数*/
        Integer askNumberDay = askBuyMapper.getNumberByDay(user.getId());
        /*今日成交数*/
        Integer dealNumeberDay = orderMapper.getdealNumberByDayByNotCancelledAndNotWaitingPaymentAndClosed(user.getId());
        /*历史求购数*/
        Integer askNumber = askBuyMapper.getAskNumber(user.getId());
        /*历史成交数*/
        Integer dealNumber = orderMapper.getDealNumberByNotCancelledAndNotWaitingPaymentAndClosed(user.getId());
        NumberFormat percentInstance = NumberFormat.getPercentInstance();
        String realRate = null;
        if (askNumber == 0) {
            realRate = "0";
        } else {
            /*实单率*/
            realRate = percentInstance.format(dealNumber / askNumber);
        }
        map.put("askNumberDay", askNumberDay);
        map.put("dealNumeberDay", dealNumeberDay);
        map.put("askNumber", askNumber);
        map.put("dealNumber", dealNumber);
        map.put("realRate", realRate);
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public ServerResponse merchantRankList() {
        List<SellerRankListDto> list = orderMapper.merchantRankList();
        for (SellerRankListDto sellerRankListDto : list) {
            Merchant merchant = merchantMapper.selectByPrimaryKey(sellerRankListDto.getId());
            sellerRankListDto.setLogo(merchant.getLogo());
            sellerRankListDto.setName(merchant.getName());
            sellerRankListDto.setAddress(merchant.getAddress());
            sellerRankListDto.setQrCodePicture(merchant.getQrCodePicture());
        }
        return ServerResponse.createBySuccess(list);
    }

    @Override
    public ServerResponse checkAskBuyById(String id) {
        AskBuyDetailDto askBuyDetailDto = askBuyMapper.checkAskBuyById(Long.valueOf(id));
        askBuyDetailDto.setQuotationTempDtoList(new ArrayList<>());
        Integer merchantId = askBuyDetailDto.getMerchantId();
        //平台求购 求购单里的merchantId为null或MerchantName()为空
        if (StringUtils.isEmpty(askBuyDetailDto.getMerchantName()) || merchantId == null) {
            //找出平台求购匹配的商家数
            int matchNum = 0;
            List<Quotation> listByid = quotationMapper.getListByid(Long.valueOf(id));
            if (listByid != null) {
                matchNum = listByid.size();
            }

            askBuyDetailDto.setMatchMerchantNum(String.valueOf(matchNum));
        }
        //指定商家求购默认匹配商家数为1
        if (!StringUtils.isEmpty(askBuyDetailDto.getMerchantName()) || merchantId != null) {
            askBuyDetailDto.setMatchMerchantNum("1");
        }
        //判断已报价商家数
        //指定商家求购的已报价商家数根据求购状态来判断及相关信息显示
        if (!StringUtils.isEmpty(askBuyDetailDto.getMerchantName()) || merchantId != null) {
            AskBuy askBuy = askBuyMapper.selectByPrimaryKey(askBuyDetailDto.getId());
            Integer status = askBuy.getStatus();//求购状态
            Quotation quotation = quotationMapper.selectByAskBuyIdAndMerchantId(askBuy.getId(), Long.valueOf(merchantId));
//          Quotation quotation = quotationMapper.selectByPrimaryKey(Long.valueOf(merchantId));
            Integer status1;
            if (quotation != null) {
                status1 = quotation.getStatus();//报价状态
            } else {
                status1 = 0;
            }
            List<AskInfo> infoList;
            List<QuotationTempDto> quotationList = quotationMapper.getQuotationTempDtoListByid(Long.valueOf(id));//查询出来的报价信息列表
            if (CollectionUtils.isNotEmpty(quotationList) && quotationList.size() == 1) {
                infoList = askInfoMapper.getInfoListAndPriceByAskId(askBuyDetailDto.getId());
            } else {
                infoList = askInfoMapper.getInfoListByAskId(askBuyDetailDto.getId());
            }
            askBuyDetailDto.setAskInfoList(infoList);//求购时添加的求购商品
            for (Quotation quotation1 : quotationList) {
                if (quotation1.getTaxPoint() == null) {
                    quotation1.setTaxPoint(new BigDecimal(0));
                }
                if (quotation1.getTaxation() == null) {
                    quotation1.setTaxation(new BigDecimal(0));
                }
                if (quotation1.getFreight() == null) {
                    quotation1.setFreight(new BigDecimal(0));
                }
            }
            if (status == null) {
                status = 0;
            }
            if (status == 0) {
                askBuyDetailDto.setStatus(status);
                if (status1 == 1) {
                    askBuyDetailDto.setOfferMerchantNum("1");
                    askBuyDetailDto.setQuotationTempDtoList(quotationList);
                } else {
                    askBuyDetailDto.setOfferMerchantNum("0");
                }
            } else if (status == 1) {
                askBuyDetailDto.setStatus(status);
                if (status1 == 1) {
                    askBuyDetailDto.setOfferMerchantNum("1");
                    askBuyDetailDto.setQuotationTempDtoList(quotationList);
                } else {
                    askBuyDetailDto.setOfferMerchantNum("0");
                }
            } else if (status == 2) {
                askBuyDetailDto.setStatus(status);
                if (status1 == 1) {
                    askBuyDetailDto.setOfferMerchantNum("1");
                    askBuyDetailDto.setQuotationTempDtoList(quotationList);
                } else {
                    askBuyDetailDto.setOfferMerchantNum("0");
                }
            } else {
                askBuyDetailDto.setStatus(status);
                if (status1 == 1) {
                    askBuyDetailDto.setOfferMerchantNum("1");
                    askBuyDetailDto.setQuotationTempDtoList(quotationList);
                } else {
                    askBuyDetailDto.setOfferMerchantNum("0");
                }
            }
        }

        //平台发起求购的已报价商家数根据求购状态来判断及相关信息显示
        if (StringUtils.isEmpty(askBuyDetailDto.getMerchantName()) || merchantId == null) {
            AskBuy askBuy = askBuyMapper.selectByPrimaryKey(askBuyDetailDto.getId());
            Integer status = askBuy.getStatus();//求购状态

            List<QuotationTempDto> lists = new ArrayList<>();//把报价行情表里状态为“卖家已报价”的状态的报价信息添加到新的集合里
            List<QuotationTempDto> quotationList = quotationMapper.getQuotationTempDtoListByid(Long.valueOf(id));//查询出来的报价信息列表
            List<AskInfo> infoList;
            if (CollectionUtils.isNotEmpty(quotationList) && quotationList.size() == 1) {
                infoList = askInfoMapper.getInfoListAndPriceByAskId(askBuyDetailDto.getId());
            } else {
                infoList = askInfoMapper.getInfoListByAskId(askBuyDetailDto.getId());
            }
            askBuyDetailDto.setAskInfoList(infoList);//求购时添加的求购商品

            for (QuotationTempDto quotation1 : quotationList) {
                if (quotation1.getTaxPoint() == null) {
                    quotation1.setTaxPoint(new BigDecimal(0));
                }
                if (quotation1.getTaxation() == null) {
                    quotation1.setTaxation(new BigDecimal(0));
                }
                if (quotation1.getFreight() == null) {
                    quotation1.setFreight(new BigDecimal(0));
                }
                if (quotation1.getStatus() == 1) {
                    lists.add(quotation1);
                }
            }
            if (status == null) {
                status = 0;
            }

            if (status == 0) {
                askBuyDetailDto.setStatus(status);
                if (lists.size() > 0) {
                    askBuyDetailDto.setOfferMerchantNum(String.valueOf(lists.size()));
                    askBuyDetailDto.setQuotationTempDtoList(lists);
                } else {
                    askBuyDetailDto.setOfferMerchantNum("0");
                }
            } else if (status == 1) {
                askBuyDetailDto.setStatus(status);
                if (lists.size() > 0) {
                    askBuyDetailDto.setOfferMerchantNum(String.valueOf(lists.size()));
                    askBuyDetailDto.setQuotationTempDtoList(lists);
                } else {
                    askBuyDetailDto.setOfferMerchantNum("0");
                }
            } else if (status == 2) {
                askBuyDetailDto.setStatus(status);
                if (lists.size() > 0) {
                    askBuyDetailDto.setOfferMerchantNum(String.valueOf(lists.size()));
                    askBuyDetailDto.setQuotationTempDtoList(lists);
                } else {
                    askBuyDetailDto.setOfferMerchantNum("0");
                }
            } else {
                askBuyDetailDto.setStatus(status);
                if (lists.size() > 0) {
                    askBuyDetailDto.setOfferMerchantNum(String.valueOf(lists.size()));
                    askBuyDetailDto.setQuotationTempDtoList(lists);
                } else {
                    askBuyDetailDto.setOfferMerchantNum("0");
                }
            }
        }

        String businessScope = askBuyDetailDto.getMerchantProcess();
        if (!StringUtils.isEmpty(businessScope)) {
            String[] split = businessScope.split("-");
            if (split.length > 0) {
                String str = "";
                for (String s : split) {
                    if (s.equalsIgnoreCase("1")) {
                        str += "风类 ";
                    } else if (s.equalsIgnoreCase("2")) {
                        str += "水类 ";
                    } else if (s.equalsIgnoreCase("3")) {
                        str += "电类 ";
                    } else if (s.equalsIgnoreCase("4")) {
                        str += "消防类 ";
                    } else {
                        str += s;
                    }
                }
                askBuyDetailDto.setMerchantProcess(str);
            }
        }
        return ServerResponse.createBySuccess(askBuyDetailDto);
    }

    @Override
    public ServerResponse cancleQuotation(String id) {
        AskBuy askBuy = askBuyMapper.selectByPrimaryKey(Long.valueOf(id));
        askBuy.setStatus(2);
        int i = askBuyMapper.updateByPrimaryKeySelective(askBuy);
        return i == 1 ? ServerResponse.createBySuccessMessage("修改成功") : ServerResponse.createByError();
    }

    @Override
    public ServerResponse offerBuy(String quId, String asId) {
        AskBuy askBuy = askBuyMapper.selectByPrimaryKey(Long.valueOf(asId));
        Quotation quotation = quotationMapper.selectByPrimaryKey(Long.valueOf(quId));
        List<Address> addressList = addressMapper.getAddressList(askBuy.getUserId());
        ArrayList<PickerDto> pickerDtos = new ArrayList<>();
        for (Address address : addressList) {
            PickerDto pickerDto = new PickerDto();
            pickerDto.setAddressId(address.getId().toString());
            pickerDto.setPickAddress(address.getAddress());
            pickerDto.setPickerName(address.getName());
            pickerDto.setPickerPhone(address.getPhone());
            pickerDtos.add(pickerDto);
        }
        Merchant merchant = merchantMapper.selectByPrimaryKey(quotation.getMerchantId());
        BuyDto buyDto = new BuyDto();
        buyDto.setMerchant(merchant);
        buyDto.setList(pickerDtos);
        return ServerResponse.createBySuccess(buyDto);
    }

    @Override
    public ServerResponse buyForCreatOrder(String merchantId, String quotationId, String addressId,
                                           String money, Integer invoice, String remark, User user) {
        Order order = new Order();
        order.setOrderNo(CommonUtils.generateUUID());
        order.setMerchantId(Long.valueOf(merchantId));
        Merchant merchant = merchantMapper.selectByPrimaryKey(Long.valueOf(merchantId));
        order.setMerchantName(merchant.getName());
        order.setQuotationId(Long.valueOf(quotationId));
        order.setAddressId(Long.valueOf(addressId));
        Address address = addressMapper.selectByPrimaryKey(Long.valueOf(addressId));
        order.setUserId(address.getUserId());
        order.setMoney(new BigDecimal(money));
        order.setPayment(new BigDecimal(money));
        Quotation quotation = quotationMapper.selectByPrimaryKey(Long.valueOf(quotationId));
        order.setPostage(quotation.getFreight());
        order.setStatus(0);
        if (merchant.getId() == 1) {
            order.setSelfSupport(1);
        } else {
            order.setSelfSupport(0);
        }
        order.setBrokerage(new BigDecimal(money).multiply(new BigDecimal(merchant.getCommission())));
        order.setRemark(remark);
        int i = orderMapper.insertSelective(order);
        return i > 0 ? ServerResponse.createBySuccessMessage("添加成功") : ServerResponse.createByError();
    }

    @Override
    public ServerResponse deletQuotation(Long askId) {
        List<Long> list = quotationInfoMapper.getIdsByAskId(askId);
        List<Long> quotationIdList = quotationMapper.getAllQuotationId(askId);
        for (Long newList : quotationIdList) {
            Integer count = orderMapper.getOrderByQuotationId(newList);
            if (!new Integer(0).equals(count) && count != null) {
                return ServerResponse.createByErrorMessage("已生成订单,无法删除求购");
            }
        }
        if (CollectionUtils.isNotEmpty(list)) {
            quotationInfoMapper.deleteByIds(list);
        }
        quotationMapper.deleteByAskId(askId);
        askInfoMapper.deleteByaskId(askId);
        askBuyMapper.deleteByPrimaryKey(askId);
        return ServerResponse.createBySuccessMessage("删除成功");
    }

    @Override
    public ServerResponse appointAskBuyList(User user, Integer status, String startDate,
                                            String endDate, Page page) {

        HashMap<Object, Object> map = Maps.newHashMap();
        map.put("userId", user.getId());
        map.put("status", status);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
        List<AppointAskBuyDto> list = quotationMapper.getappointAskBuyList(map);
        for (AppointAskBuyDto appointAskBuyDto : list) {
            String id = appointAskBuyDto.getId();
            AskBuy askBuy = askBuyMapper.selectByPrimaryKey(Long.valueOf(id));
            if (StringUtils.isEmpty(askBuy.getMerchantName())) {
                appointAskBuyDto.setMerchantName("");
            } else {
                appointAskBuyDto.setMerchantName(askBuy.getMerchantName());
            }
//            if (appointAskBuyDto.getStatus().length() == 1 && !StringUtils.isEmpty(appointAskBuyDto.getStatus())) {
//                Long status1 = Long.valueOf(appointAskBuyDto.getStatus());
//                if (status1 == 0) {
//                    appointAskBuyDto.setStatus("未报价");
//                } else if (status1 == 1) {
//                    appointAskBuyDto.setStatus("已报价");
//                } else if (status1 == 2) {
//                    appointAskBuyDto.setStatus("已拒绝");
//                } else {
//                    appointAskBuyDto.setStatus("已取消");
//                }
//            }
//            if (StringUtils.isEmpty(appointAskBuyDto.getStatus())) {
//                appointAskBuyDto.setStatus("未报价");
//            }
        }
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse checkOrderDetail(String id) {
        return newOrderService.getOrderDetailByBuyer(id);
    }

    /**
     * 取消/确认/删除订单
     * 0 1 此接口不处理 如果是修为2 3 4 5双方都需要改 67 只改自己的 但是删除订单需要看原来订单的状态
     *
     * @param id
     * @return
     */
    @Override
    public ServerResponse updateOrderStatus(Long id, Integer status, Long userId) {
        BuyerAndSellerDto buyerAndSeller = orderMapper.getBuyerAndSellerById(id);
        Order order = orderMapper.selectByPrimaryKey(id);
        if (status == 2 || status == 3 || status == 4 || status == 5) {
            order.setStatus(status);
            order.setStatusSeller(status);
            if (status == 2) {
                order.setSendTime(new Date());
            } else if (status == 3) {
                order.setEndTime(new Date());
            } else if (status == 5) {
                order.setCloseTime(new Date());
            }
        } else if (status == 6 || status == 7) {
            //删除订单需要看原来自己的订单的状态
            if (order.getStatus() == 4 || order.getStatus() == 5) {
                if (userId.equals(buyerAndSeller.getBuyer())) {
                    order.setStatus(6);
                }
            } else if (order.getStatus() == 3) {
                if (userId.equals(buyerAndSeller.getBuyer())) {
                    order.setStatus(7);
                }
            }
            if (order.getStatusSeller() == 4 || order.getStatusSeller() == 5) {
                if (userId.equals(buyerAndSeller.getSeller())) {
                    order.setStatusSeller(6);
                }
            } else if (order.getStatusSeller() == 3) {
                if (userId.equals(buyerAndSeller.getSeller())) {
                    order.setStatusSeller(7);
                }
            }
        } else {
            return ServerResponse.createByErrorMessage("状态异常");
        }
        order.setUpdateTime(new Date());

        int i = orderMapper.updateByPrimaryKeySelective(order);
        return i > 0 ? ServerResponse.createBySuccess() : ServerResponse.createByError();
    }

    /**
     * @param id 订单id
     * @return
     */
    @Override
    public ServerResponse delOrderDetail(String id) {
        Order order = orderMapper.selectByPrimaryKey(Long.valueOf(id));
        if (order != null && order.getStatus() == 3) {
            order.setStatus(7);
        } else {
            order.setStatus(6);
        }
        int i = orderMapper.updateByPrimaryKey(order);
        return i > 0 ? ServerResponse.createBySuccessMessage("删除成功") : ServerResponse.createByError();
    }

    @Override
    public ServerResponse getAddressList(Long userId) {
        List<Address> addressList = addressMapper.getAddressList(userId);
        return ServerResponse.createBySuccess(addressList);
    }

    @Override
    public ServerResponse getAddress(Long userId) {
        Address defuAddress = addressMapper.getDefuAddress(userId);
        return ServerResponse.createBySuccess(defuAddress);
    }

    @Override
    public ServerResponse setAddress(Long userId, Long id) {
        int i = addressMapper.recoverStatus(userId, id);
        Address address = addressMapper.selectByPrimaryKey(id);
        address.setStatus(0);
        int j = addressMapper.updateByPrimaryKeySelective(address);
        return i > 0 && j > 0 ? ServerResponse.createBySuccess() : ServerResponse.createByError();
    }

    /**
     * 小程序端：个人中心-自营订单
     *
     * @return
     */
    @Override
    public ServerResponse WXselforder(Integer status, Page page, Long userId) {
        PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
        //自营商家的店铺id
        Long merchantId = 1L;
        List<WXorderDto> list = orderMapper.WXselforder(status, userId, merchantId);
        for (WXorderDto dto : list) {
            //null != dto.getQuotationId()表示为求购订单
            if (null != dto.getQuotationId()) {
                List<OrderItemTimeDto> orderItemTimeDtos = newOrderService.newGetOrderItemByOrderId(dto.getId(), dto.getQuotationId());
                dto.setList(orderItemTimeDtos);
            }
        }
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * 小程序端：个人中心-第三方订单
     *
     * @param status
     * @param page
     * @param userId
     * @return
     */
    @Override
    public ServerResponse WXthirdorder(Integer status, Page page, Long userId) {
        PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
        Long merchantId = 0L;//非自营商家的店铺id
        List<WXorderDto> list = orderMapper.WXselforder(status, userId, merchantId);
        for (WXorderDto dto : list) {
            if (null != dto.getQuotationId()) {
                List<OrderItemTimeDto> orderItemTimeDtos = newOrderService.newGetOrderItemByOrderId(dto.getId(), dto.getQuotationId());
                dto.setList(orderItemTimeDtos);
            }
        }
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse repeatQuotation(Long askId, User user) {
        User userScore = userMapper.selectByPrimaryKey(user.getId());
        Long integralId = Long.valueOf(6);
        //查询积分信息
        SocerManager socerManager = socerManagerMapper.selectByPrimaryKey(integralId);
        if (new Integer(1).equals(socerManager.getStatus())) {
            if (userScore.getScore() < Integer.parseInt(socerManager.getSocer())) {
                return ServerResponse.createByErrorMessage("积分不足");
            }
        }
        AskBuy askBuy = new AskBuy();
        askBuy.setId(askId);
        askBuy.setStatus(0);
        askBuy.setCreateTime(new Date());
        askBuy.setUpdateTime(new Date());
        List<Long> quotationIdList = quotationMapper.getAllQuotationId(askId);
        if (quotationIdList.size() > 0 && quotationIdList != null) {
            for (Long newList : quotationIdList) {
                Integer count = orderMapper.getOrderByQuotationId(newList);
                if (!new Integer(0).equals(count) && count != null) {
                    return ServerResponse.createByErrorMessage("已有生成订单,请重新在首页发布求购");
                }
            }
            quotationIdList.forEach(newList -> {
                int i = quotationInfoMapper.deleteByQaId(newList);
                int k = quotationMapper.deleteByPrimaryKey(newList);
            });
        }
        List<Quotation> askBuyStoreList = quotationMapper.getAskBuyStore(askId, 10);
        int askBuySuccess = askBuyMapper.updateByPrimaryKeySelective(askBuy);
        askBuyStoreList.forEach(askBuyStore -> quotationMapper.insertSelective(askBuyStore));
        return ServerResponse.createBySuccessMessage("发起求购成功");
    }

    @Override
    public ServerResponse WxSelfOperatedBuy(Integer status, Page page, Long userId, Long merchantId) {
        PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
        List<WxAskBuyListDto> list = askBuyMapper.getWxAskBuyListByUserId(status, userId, merchantId);
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Override
    public ServerResponse WxOperatedBuy(User user, Page page, String startDate, String endDate, Integer status) {
        //TODO 以前的代码优化与否后期决定
        HashMap<Object, Object> map = Maps.newHashMap();
        map.put("status", status);
        map.put("userId", user.getId());
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
        List<AskBuyDto> askBuyDtoList = askBuyMapper.getAskList(map);
        for (AskBuyDto askBuyDto : askBuyDtoList) {
            //统计平台求购匹配的商家总共有几家
            Integer count = quotationMapper.countNum(Integer.valueOf(askBuyDto.getAskBuyId()));
            //得到匹配商家里最新报价一家的的报价信息
            Quotation quotation = quotationMapper.getNewPrice(Integer.valueOf(askBuyDto.getAskBuyId()));
            //得到匹配商家里所有已经报价了的商家个数
            Integer countTime = quotationMapper.countNumByNull(Integer.valueOf(askBuyDto.getAskBuyId()));
            askBuyDto.setMatchMerchant(String.valueOf(count));
            askBuyDto.setOfferMerchant(String.valueOf(countTime));
            if (quotation == null) {
                askBuyDto.setFreight("0");
                askBuyDto.setTaxation("0");
                askBuyDto.setTaxPoint("0");
                askBuyDto.setPrice("0");
                askBuyDto.setNewPrice("0");
            } else {
                if (quotation.getPrice() == null || "".equals(quotation.getPrice())) {
                    askBuyDto.setNewPrice("0");
                } else {
                    askBuyDto.setNewPrice(quotation.getPrice().toString());
                }
                if (quotation.getTaxPoint() == null) {
                    askBuyDto.setTaxPoint("0");
                } else {
                    askBuyDto.setTaxPoint(quotation.getTaxPoint().toString());
                }
                if (quotation.getTaxation() == null) {
                    askBuyDto.setTaxation("0");
                } else {
                    askBuyDto.setTaxation(quotation.getTaxation().toString());
                }
                if (quotation.getFreight() == null) {
                    askBuyDto.setFreight("0");
                } else {
                    askBuyDto.setFreight(quotation.getFreight().toString());
                }
                if (quotation.getPrice() == null) {
                    askBuyDto.setPrice("0");
                } else {
                    askBuyDto.setPrice(quotation.getPrice().toString());
                }
            }
        }
        PageInfo pageInfo = new PageInfo(askBuyDtoList);
        return ServerResponse.createBySuccess(pageInfo);

    }


    @Override
    public ServerResponse WxAppointAskBuyList(User user, Integer status, String startDate,
                                              String endDate, Page page) {

        HashMap<Object, Object> map = Maps.newHashMap();
        map.put("userId", user.getId());
        map.put("status", status);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
        List<AppointAskBuyDto> list = quotationMapper.getappointAskBuyList(map);
        for (AppointAskBuyDto appointAskBuyDto : list) {
            String businessScope = appointAskBuyDto.getBusinessScope();
            if (!StringUtils.isEmpty(businessScope)) {
                String[] split = businessScope.split("-");
                if (split.length > 0) {
                    String str = "";
                    for (String s : split) {
                        if (s.equalsIgnoreCase("1")) {
                            str += "风类 ";
                        } else if (s.equalsIgnoreCase("2")) {
                            str += "水类 ";
                        } else if (s.equalsIgnoreCase("3")) {
                            str += "电类 ";
                        } else if (s.equalsIgnoreCase("4")) {
                            str += "消防类 ";
                        } else {
                            str += s;
                        }
                    }
                    appointAskBuyDto.setBusinessScope(str);
                }
            }
        }
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse wxSelfBuyOrder(Integer status, Long userId, Page page) {
        PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
        List<WxSelfBuyOrderDto> list = orderMapper.getWxOrderByUserId(userId, status);
        PageInfo pageInfo = new PageInfo(list);
        if (CollectionUtils.isEmpty(list)) {
            return ServerResponse.createBySuccess(pageInfo);
        }
        List<WxAskBuyOrderListDto> orderList = orderMapper.getWxAskBuyOrderListByUserId(userId, status);
        for (WxSelfBuyOrderDto wxSelfBuyOrderDto : list) {
            List<WxAskBuyOrderListDto> newList = new ArrayList<>();
            for (WxAskBuyOrderListDto wxAskBuyOrderListDto : orderList) {
                if (wxAskBuyOrderListDto.getOrderId().equals(wxSelfBuyOrderDto.getOrderId())) {
                    newList.add(wxAskBuyOrderListDto);
                }
            }
            wxSelfBuyOrderDto.setWxAskBuyOrderListDtos(newList);
        }
        return ServerResponse.createBySuccess(pageInfo);
    }

}
